import { defineStore } from 'pinia'

export const useAdminStore = defineStore('admin', {
  state: () => ({
    // 用户信息
    userInfo: null,
    // 用户权限列表
    permissions: [],
    // 用户角色列表
    roles: [],
    // token信息
    token: null
  }),

  getters: {
    // 判断是否已登录
    isLoggedIn: (state) => !!state.token,
    
    // 获取用户信息
    getUserInfo: (state) => state.userInfo,
    
    // 获取权限列表
    getPermissions: (state) => state.permissions,
    
    // 获取角色列表
    getRoles: (state) => state.roles
  },

  actions: {
    // 设置用户信息
    setUserInfo(info) {
      this.userInfo = info
    },

    // 设置权限列表
    setPermissions(permissions) {
      this.permissions = permissions
    },

    // 设置角色列表
    setRoles(roles) {
      this.roles = roles
    },

    // 设置token
    setToken(token) {
      this.token = token
    },

    // 登录成功后的处理
    handleLoginSuccess(data) {
      const { token, userInfo, permissions, roles } = data
      this.setToken(token)
      this.setUserInfo(userInfo)
      this.setPermissions(permissions)
      this.setRoles(roles)
    //   console.log('登录成功', data)
    },

    // 退出登录
    logout() {
      this.token = null
      this.userInfo = null
      this.permissions = []
      this.roles = []
    },

    // 检查是否有某个权限
    hasPermission(permission) {
      return this.permissions.includes(permission)
    },

    // 检查是否有某个角色
    hasRole(role) {
      return this.roles.includes(role)
    }
  },

  // 开启数据持久化
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'admin',
        storage: localStorage,
        paths: ['token', 'userInfo', 'permissions', 'roles']
      }
    ]
  }
})